<template>
  <div>
    <el-header>
      <div class="right">
        <span v-show="$store.state.usersInfo == ''">
          <span class="login span" @click="loginIfo">登录</span>
          <span @click="enroll" class="span">注册</span>
        </span>

        <!-- 用户退出登录弹框 -->
        <el-popover
          placement="top"
          width="160"
          v-model="visible"
          v-show="$store.state.usersInfo != ''"
        >
          <p>确认退出？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible = false">取消</el-button>
            <el-button size="mini" @click="delUser" type="primary">确定</el-button>
          </div>
          <el-button slot="reference" class="btuom"
            >欢迎：{{ $store.state.usersInfo.userName }}</el-button
          >
        </el-popover>
        <span class="span" @click="$router.push('/order')">我的订单</span>
        <span class="span" @click="$router.push('/collect')">我的收藏</span>
        <div @click="$router.push('/shopping')">
          <i class="el-icon-shopping-cart-full"></i>购物车(0)
        </div>
      </div>
    </el-header>
    <div class="nav">
      <!-- logo图标 -->
      <img src="/img/logo.png" alt="" />
      <!-- 选项卡 -->
      <el-menu
        mode="horizontal"
        router
        active-text-color="#409EFF"
        :default-active="this.$route.path"
      >
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/goods">所有商品</el-menu-item>
        <el-menu-item index="/my">关于我们</el-menu-item>
      </el-menu>
      <!-- 搜索框 -->
      <el-input placeholder="请输入内容" v-model="serch" style="width: 300px">
        <el-button slot="append" icon="el-icon-search" @click="searchClick"></el-button>
      </el-input>
    </div>

    <!-- 登录 -->
    <el-dialog title="登录" :visible.sync="loginFlag">
      <el-form
        :model="loginForm"
        status-icon
        :rules="loginRules"
        ref="loginForm"
        class="demo-ruleForm"
      >
        <!-- 账号 -->
        <el-form-item prop="userName">
          <el-input
            type="text"
            v-model="loginForm.userName"
            placeholder="请输入用户名"
            autocomplete="off"
            style="width: 300px"
          >
            <i slot="prefix" class="el-icon-s-custom"></i>
          </el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            placeholder="请输入用户密码"
            autocomplete="off"
            style="width: 300px"
          >
            <i slot="prefix" class="el-icon-view"></i>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="loginFlagYes('loginForm')" style="width: 100%"
          >登录</el-button
        >
      </div>
    </el-dialog>

    <!-- 注册 -->
    <el-dialog title="注册" :visible.sync="enrollFlag">
      <el-form
        :model="enrollForm"
        status-icon
        :rules="enrollRules"
        ref="enrollForm"
        class="demo-ruleForm"
      >
        <!-- 注册用户名 -->
        <el-form-item prop="userName">
          <el-input
            type="text"
            v-model="enrollForm.userName"
            placeholder="请输入账号"
            autocomplete="off"
            style="width: 300px"
          >
            <i slot="prefix" class="el-icon-s-custom"></i>
          </el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="enrollForm.password"
            placeholder="请输入密码"
            autocomplete="off"
            style="width: 300px"
          >
            <i slot="prefix" class="el-icon-view"></i>
          </el-input>
        </el-form-item>

        <!-- 注册确认密码 -->
        <el-form-item prop="checkPass">
          <el-input
            type="password"
            v-model="enrollForm.checkPass"
            placeholder="请输入确认密码"
            autocomplete="off"
            style="width: 300px"
          >
            <i slot="prefix" class="el-icon-view"></i>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="enrollFlagYes('enrollForm')" style="width: 100%"
          >注册</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import loginApi from "@/api/MiuiLoginAPI.js";
export default {
  /**beforeUpdate
   * 针对视图层的：也就是说当视图层的数据发生该百年或者渲染，才会触发这个生命周期函数
   */
  // beforeUpdate() {
  //   this.activeIndex = this.$route.path;
  // },
  name: "",
  data() {
    // 用户名
    var validateName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        if (this.masg == "004") {
          callback(new Error("用户已被注册"));
        }
        callback();
      }
    };
    // 验证密码
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.enrollForm.checkPass !== "") {
          this.$refs.enrollForm.validateField("checkPass");
        }
        callback();
      }
    };
    // 验证密码二次确认
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.enrollForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // 登录数据
      loginForm: {
        userName: "",
        password: "",
      },
      // 注册数据
      enrollForm: {
        userName: "",
        password: "",
        checkPass: "",
      },

      // 登录校验
      loginRules: {
        userName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            message: "字母开头,长度5-16之间,允许字母数字下划线",
            pattern: /^[a-zA-Z]\w{4,15}$/,
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            message: "字母开头,长度6-18之间,允许字母数字和下划线",
            pattern: /^[a-zA-Z]\w{5,17}$/,
            trigger: "blur",
          },
        ],
      },

      // 注册校验
      enrollRules: {
        userName: [
          { validator: validateName, trigger: "blur" },
          {
            message: "字母开头,长度5-16之间,允许字母数字下划线",
            pattern: /^[a-zA-Z]\w{4,15}$/,
            trigger: "blur",
          },
        ],
        password: [
          { validator: validatePass, trigger: "blur" },
          {
            message: "字母开头,长度6-18之间,允许字母数字下划线",
            pattern: /^[a-zA-Z]\w{5,17}$/,
            trigger: "blur",
          },
        ],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
      },

      serch: "",
      activeIndex: "",
      loginFlag: false,
      enrollFlag: false,
      visible: false,
      masg: "",
      user: "",
    };
  },

  mounted() {},
  methods: {
    // 搜索
    searchClick() {
      this.$router.push({ path: "/goods", query: { search: this.serch } });
      this.serch = "";
    },
    // 登录
    loginIfo() {
      this.loginFlag = true;
    },
    // 登录点击确定时触发
    loginFlagYes(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await loginApi.userLogin(this.loginForm);
          // console.log(res);
          if (res.code == "001") {
            this.$notify({
              title: "登录成功",
              message: res.msg,
              type: "success",
            });
            this.loginForm = {}; //清空登录表单信息
            this.loginFlag = false; //登录成功关闭弹框
            // 获取到用户信息存储到vuex 进行持久化
            this.$store.commit("userName", res.user);
          }
        } else {
          return false;
        }
      });
    },

    // 注册
    enroll() {
      this.enrollFlag = true;
    },
    // 注册点击确认时触发
    enrollFlagYes(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 用户注册成功
          const res = await loginApi.userEnroll(this.enrollForm);
          // console.log(res);
          if (res.code == "001") {
            // console.log(res.msg);
            this.$notify({
              title: "注册成功",
              message: res.msg,
              type: "success",
            });
            // 注册成功关闭弹框
            this.enrollFlag = false;
            // 清空注册文本框的值
            this.enrollForm = {};
          } else {
            this.masg = res.code;
          }
        } else {
          return false;
        }
      });
    },
    // 当第一个input状态改变的时候触发请求验证接口
    // async enrollUser(){
    //     const res = await loginApi.userVerify(this.enrollForm.userName)
    //     console.log(res);
    //     this.masg = res.code
    // }

    //退出
    delUser() {
      sessionStorage.removeItem("user");
      this.visible = false;
      this.$notify({
        title: "成功",
        message: "退出成功",
        type: "success",
      });
      // 退出时删除用户名信息
      this.$store.commit("delUser");
    },
  },
  computed: {},
  watch: {},
};
</script>

<style lang="scss" scoped>
.el-header {
  width: 100%;
  height: 40px !important;
  background: #3d3d3d;
  color: #b0b0b0;
  margin-bottom: 20px;
  .right {
    float: right;
    line-height: 40px;
    margin-right: 60px;
    font-size: 14px;
    .span:hover {
      color: #fff;
      cursor: pointer;
    }
    & > span:nth-child(3) {
      margin: 0 20px;
    }
    & > span:nth-child(4) {
      margin-right: 20px;
    }
    & > div {
      width: 120px;
      background: #424242;
      display: inline-block;
      text-align: center;
    }
    & > div:hover {
      color: orangered;
      background: #fff;
      cursor: pointer;
    }
    i {
      margin-right: 5px;
    }
  }
  .login:after {
    content: "|";
    margin: 0 5px;
    color: #777;
  }
}
.nav {
  margin: 0 40px;
  border-bottom: 1px solid #ddd;
  display: flex;
  position: relative;
  justify-content: space-between;
  align-items: center;
  .el-tabs {
    position: absolute;
    top: 20px;
    left: 300px;
  }
}
</style>
